//
//  KZRegexHelper.swift
//  KZSwiftMoudel
//
//  Created by 朱凯 on 2018/5/4.
//  Copyright © 2018年 JooKey. All rights reserved.
//

import Foundation

class KZRegexHelper {
    let regex: NSRegularExpression?
    init(_ pattern: String) {
        if let regex = try? NSRegularExpression.init(pattern: pattern, options: .caseInsensitive) {
            self.regex = regex
        } else {
            regex = nil
        }
    }
    
    func matches(_ string: String) -> Bool {
        if let result = regex?.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) {
            print(result)
            return result.count > 0
        } else {
            print("regex 未初始化或初始化失败")
            return false
        }
    }
}

enum KZRegexCommonPattern: String {
    case mail       = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
    case url        = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
    case slug       = "^[a-z0-9-]+$"
    case password   = "^[a-z0-9_-]{6,18}$"
    case username   = "^[a-z0-9_-]{3,16}$"
    case hexValue   = "^#?([a-f0-9]{6}|[a-f0-9]{3})$"
}


// 定义一个计算符
precedencegroup KZRegexMatchPrecedence {
    associativity: none
    higherThan: DefaultPrecedence
}
infix operator =~: KZRegexMatchPrecedence
func =~(lhs: String, rhs: String) -> Bool {
    return KZRegexHelper(rhs).matches(lhs)
}

